package com.xtianzhuang.www.study2019.practice.leetcode.algorithm;

/**
 * 给出一个 32 位的有符号整数，你需要将这个整数中每位上的数字进行反转。
 * @author xtian.zhuang
 * @date Jul 19, 2019
 */
public class Question7 {
	public static void main(String[] args) {
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Integer.MIN_VALUE);
		System.out.println(reverse(123));
		System.out.println(reverse(120));
		System.out.println(reverse(-120));
		System.out.println(reverse(-123));
		// 9646324351
		// System.out.println(reverse(9646324351));
		// Line 28: java.lang.NumberFormatException: For input string: "9646324351"
	}

	public static int reverse(int x) {

		String[] str = String.valueOf(x).split("");
		String newStr = "";
		if (x > 0) {
			for (int i = str.length - 1; i >= 0; i--) {
				if (newStr.equals("") && !str[i].equals("0")) {
					newStr = newStr + str[i];
				} else if (!newStr.equals("")) {
					newStr = newStr + str[i];
				}
			}
		} else if (x < 0) {
			for (int i = str.length - 1; i > 0; i--) {
				if (newStr.equals("") && !str[i].equals("0")) {
					newStr = newStr + str[i];
				} else if (!newStr.equals("")) {
					newStr = newStr + str[i];
				}
			}
			newStr = "-" + newStr;
		} else {
			newStr = "0";
		}
		long val = Long.valueOf(newStr);
		if (val > Integer.MAX_VALUE || val < Integer.MIN_VALUE) {
			return 0;
		}
		return (int) val;
	}
}
